/**
 * Created by admin on 2016/11/10.
 */
var assert = require('../assert');

exports.cart = function(req,res){
    var userId = assert.getUserId(req);
    if(!userId){
        res.render('error', assert.getRes(103, "获取用户信息失败", {}, true));
        return;
    }
    //获取用户的购物车数据
    var JADE_VAR = assert.getJADEVAR();
    assert.apiParseRequest('GET', '/kdShoppingItems?userId=' + userId, {}).then(function (results) {
        if(Object.keys(results).length){
            JADE_VAR.cartList = results;
            JADE_VAR.isNull = false;
        }else {
            JADE_VAR.cartList = [];
            JADE_VAR.isNull = true;
        }
        res.render('pay/cart', JADE_VAR);
    }, function (err) {
        JADE_VAR.message = "获取购物车商品失败";
        res.render('pay/cart', JADE_VAR);
    });

};

exports.orderConfirm = function (req, res) {
    var JADE_VAR = assert.getJADEVAR();
    var params = req.query.params;
    var userId = assert.getUserId(req);
    if (!userId) {
        res.render('error', assert.getRes(103, "获取用户信息失败", {}, true));
        return;
    }

    var checkedProduct = JSON.parse(new assert.base64Assert().decode(params)).products;
    var waitReq = getProductShortList(checkedProduct);
    var addressRequest = assert.apiParseRequest('GET', '/kdaddress?userId=' + userId, {});
    waitReq.push(addressRequest);
    Promise.all(waitReq).then(function (results) {

        if (results) {
            var sumPrice = 0;
            var countSum = 0;

            //排除掉地址请求结果
            JADE_VAR.addressList = results.pop();
            for (var i = 0; i < results.length; i++) {
                var count = checkedProduct[i].count;
                results[i].count = count;
                sumPrice += results[i].salePrice * count;
                countSum += results[i].count
            }
            JADE_VAR.products = results;
            JADE_VAR.chooseSumPrice = sumPrice;
            res.render('pay/pay', JADE_VAR);
        } else {
            JADE_VAR.message = "获取商品信息失败";
            res.render('error', JADE_VAR);
        }
    }, function (err) {
        JADE_VAR.message = "获取商品信息失败";
        res.render('error', JADE_VAR);
    });

    function getProductShortList(checkedProduct) {
        var productRequest = [];
        for (var i = 0; i < checkedProduct.length; i++) {
            productRequest.push(assert.apiParseRequest('GET', '/kdProduct/' + checkedProduct[i].product + '?isShort=1', {}));
        }
        return productRequest;
    }
};

exports.payment = function(req,res){
    var userId = assert.getUserId(req);
    if (!userId) {
        res.render('error', assert.getRes(103, "用户获取失败", {}, true));
        return;
    }
    var info = req.query.info;
    if (!info) {
        res.render('error', assert.getRes(102, "获取订单信息失败", {}, true));
        return;
    }
    var UserAgent = req.headers['user-agent'];
    var isWx = false;
    if (UserAgent.indexOf('MicroMessenger') != -1) {
        isWx = true;
    }
    var results = JSON.parse(new assert.base64Assert().decode(info));
    if (!results) {
        res.render('error', assert.getRes(103, "解析订单信息失败", {}, true));
        return;
    }

    var JADE_VAR = assert.getJADEVAR();
    JADE_VAR.isWx = isWx;
    JADE_VAR.orderId = results.objectId;
    JADE_VAR.payPrice = results.payPrice;
    res.render('pay/payment', JADE_VAR);
};

exports.createOrder = function(req,res, next){
    var userId = assert.getUserId(req);
    var addressId = req.body.addressId;
    var products = req.body.products;
    var remark = req.body.remark;
    if(!userId){
        res.send(assert.getRes(103,"获取用户信息失败"));
        return;
    }
    if (!addressId) {
        res.send(assert.getRes(101, "获取用户地址失败"));
        return;
    }
    if (!products) {
        res.send(assert.getRes(101, "获取购买产品信息失败"));
        return;
    }
    products = JSON.parse(products);
    console.log(products[0]);
    var data = {
        userId: userId,
        addressId: addressId,
        products: products,
        remark: remark
    };
    assert.apiParseRequest('POST', '/KdOrder', data).then(function (results) {
        if (results) {
            var info = new assert.base64Assert().encode(JSON.stringify({
                objectId: results.objectId,
                payPrice: results.payPrice
            }));
            res.send(assert.getRes(200, "生成订单成功", info));
        } else {
            res.send(assert.getRes(102, "生成订单失败"));
        }
    }, function (err) {
        res.send(assert.getRes(102, "服务器连接失败"));
    });
};

//购物车操作
exports.addToCart = function(req,res,next){
     var userId = assert.getUserId(req);
     var addCount = req.body.productCount;
     var product = req.body.product;
     if(!userId){
      res.send(assert.getRes(103,"用户未登录"));
      return;
     }
     if(!product){
      res.send(assert.getRes(101,"获取商品ID失败"));
      return;
     }
     if(!addCount){
      addCount = 1;
     }
     //请求接口
     assert.apiParseRequest('post','/kdShoppingItems?userId='+userId,{
      productId:product,
      count:addCount
     }).then(function (results) {
      res.send(assert.getRes(200,"加入购物车成功",results));
     }, function (err,error) {
      res.send(assert.getRes(102,error));
     })
};
exports.delCart = function(req,res,next){
    var userId = assert.getUserId(req);
     var deleteObj = req.body.cartId;
     if(!userId){
      res.send(assert.getRes(103,"获取用户信息失败"));
      return;
     }
     if(!deleteObj){
      res.send(assert.getRes(102,"获取购物商品信息失败"));
      return;
     }
     //请求删除接口
     assert.apiParseRequest('POST','/deletekdShoppingItems', {deleteObj:deleteObj}).then(function (results) {
      res.send(assert.getRes(200,"删除购物车数据成功"));
     }, function (error) {
      res.send(assert.getRes(102,"删除失败"));
     })
};
exports.modCartCount = function(req,res,next){
     var userId = assert.getUserId(req);
     if(!userId){
         res.send(assert.getRes(103,"获取用户信息失败"));
         return;
     }
      var cartId = req.body.cartId;
      var modType = req.body.type;

      if(!cartId || !modType){
       res.send(assert.getRes(101,"获取用户信息失败"));
       return;
      }
      var modCount = modType == 'plus' ? 1 : -1;
      //请求修改数量接口
      assert.apiParseRequest('PUT','/kdShoppingItems/'+cartId,{count:modCount}).then(function (results) {
       res.send(assert.getRes(200,"修改购物车数据成功"));
      }, function (error) {
       res.send(assert.getRes(102,"修改失败"));
 })
};

//地址操作
exports.addAddress = function(req,res,next){
    var userId = assert.getUserId(req);
    if(!userId){
        res.send(assert.getRes(103,"获取用户信息失败"));
        return;
    }
    var name = req.body.name;
    var phone = req.body.phone;
    var province = req.body.province;
    var city = req.body.city;
    var district = req.body.district;
    var address = req.body.address;
    var postcode = req.body.postcode;

    if (!name || !phone || !province || !city || !district || !address) {
        res.send(assert.getRes(102, "请完整填写收货信息"));
        return;
    }
    var data = {
        userId: userId,
        username: name,
        tel: phone,
        province: province,
        city: city,
        district: district,
        detailAddress: address,
        postcode: postcode
    };

    assert.apiParseRequest('POST', '/createkdAddress', data).then(function (results) {
        res.send(assert.getRes(200, '添加成功', results));

    }, function (err, error) {
        console.log(err);
        res.send(assert.getRes(401, '服务器错误'));
    })
};
exports.modAddress = function(req,res,next){
    var userId = assert.getUserId(req);
    if(!userId){
        res.send(assert.getRes(103,"获取用户信息失败"));
        return;
    }

    var addressId = req.body.addressId;
    if (!addressId) {
        res.send(assert.getRes(101, "获取收货地址失败"));
        return;
    }

    var name = req.body.name;
    var phone = req.body.phone;
    var province = req.body.province;
    var city = req.body.city;
    var district = req.body.district;
    var address = req.body.address;
    var postcode = req.body.postcode;

    if (!name || !phone || !province || !city || !district || !address) {
        res.send(assert.getRes(102, "请完整填写收货信息"));
        return;
    }
    var data = {
        username: name,
        tel: phone,
        province: province,
        city: city,
        district: district,
        detailAddress: address,
        postcode: postcode
    };
    assert.apiParseRequest('PUT', '/editkdAddress/' + addressId, data).then(function (results) {
        res.send(assert.getRes(200, '修改成功', results));
    }, function (err, error) {
        console.log(err);
        res.send(assert.getRes(401, '服务器错误'));
    })
};
exports.delAddress = function(req,res,next){
    var userId = assert.getUserId(req);
    if(!userId){
        res.send(assert.getRes(103,"获取用户信息失败"));
        return;
    }
    var addressId = req.body.addressId;
    if (!addressId) {
        res.send(assert.getRes(101, "获取用户地址信息失败"));
        return;
    }
    assert.apiParseRequest('DELETE', '/address/' + addressId, {}).then(function (results) {
        res.send(assert.getRes(200, "删除成功"));
    }, function (err, error) {
        res.send(assert.getRes(102, "删除失败,服务器错误"));
    })
};

